// $Id: stream.c 88 2011-10-17 18:00:11Z cedric.shih@gmail.com $
/*
 * Copyright 2011 Cedric Shih (cedric dot shih at gmail dot com)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include <stdlib.h>
#include <errno.h>
#include <string.h>

#include "log.h"

#include "stream.h"

void niortsp_stream_free(struct niortsp_stream *stream)
{
	if (!stream) {
		return;
	}

	free(stream);
}

int niortsp_stream_list_add(struct niortsp_stream_list *list,
		struct niortsp_session *session, struct niortsp_track *track,
		struct niortp_transport_param *param,
		struct niortp_transport *transport, void *transporter,
		struct niortsp_stream **ptr)
{
	int rc;
	struct niortsp_stream *stream;

	niortsp_debug("adding to list %p: %p", list, track);

	if (!(stream = calloc(1, sizeof(*stream)))) {
		rc = errno ? errno : -1;
		niortsp_error("calloc: %s", strerror(rc));
		goto finally;
	}

	stream->session = session;
	stream->track = track;
	stream->transport = transport;
	stream->transporter = transporter;
	memcpy(&stream->param, param, sizeof(stream->param));
	TAILQ_INSERT_TAIL(list, stream, entry);
	*ptr = stream;
	rc = 0;

finally:
	if (rc != 0) {
		if (stream) {
			niortsp_stream_free(stream);
		}
	}
	return rc;
}

void niortsp_stream_list_del(struct niortsp_stream_list *list,
		struct niortsp_stream *stream)
{
	niortsp_debug("deleting from list %p: %p", list, stream);

	TAILQ_REMOVE(list, stream, entry);
	niortsp_stream_free(stream);
}

struct niortsp_stream *niortsp_stream_list_find(
		struct niortsp_stream_list *list, struct niortsp_track *track)
{
	struct niortsp_stream *stream, *match = NULL;

	niortsp_debug("finding in list %p: %p", list, track);

	TAILQ_FOREACH(stream, list, entry) {
		if (track == stream->track) {
			niortsp_debug("found in list %p: %p", list, track);
			match = stream;
			break;
		}
	}

	return match;
}

void niortsp_stream_list_clear(struct niortsp_stream_list *list)
{
	struct niortsp_stream *stream;

	niortsp_debug("clearing list %p", list);

	while ((stream = TAILQ_FIRST(list))) {
		niortsp_stream_list_del(list, stream);
	}
}
